package bid.yanhj.yanhaijiang.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class AFragment extends Fragment {

    private static final String TAG = "lanbu";
    private Context mContext;
    private TextView textView;
    private Button button;

    private DataChangeListener dataChangeListener;

    public void setDataChangeListener(DataChangeListener dataChangeListener) {
        this.dataChangeListener = dataChangeListener;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
        Log.d(TAG, "onAttach: ");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_a, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated: ");
        // 当Fragment的视图创建完成后会回调
        // view 就是 onCreateView 创建返回的View
        // 组件的初始化操作

        textView = view.findViewById(R.id.fragment_tv);
        button = view.findViewById(R.id.fragment_btn);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dataChangeListener != null) {
                    String s = textView.getText().toString();
                    dataChangeListener.onDataChange(s);
                }
            }
        });
    }

    /**
     * 设置data
     * @param string
     */
    public void setData(String string) {
        if (textView != null) {
            textView.setText(string);
        }
    }

    /**
     * Activity生命周期已经走完回调
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "onActivityCreated: ");
        // 做数据的处理
        // 知识执行一次
        Bundle bundle = getArguments();
        String s = bundle.getString("data");
        textView.setText(s);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView: ");
        // 释放资源
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
        // 释放资源
    }
}
